﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;
using Microsoft.LiveFX.Client;
using Google.GData.Contacts;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;
using System.Collections;
using System.Drawing;
using ModemGSM;
using System.Resources;
using PhoneManager.LanguageText;
using System.Globalization;

namespace PhoneManager
{

    #region Enum

    public enum BookSyncEnum
    {
        None = 0,
        Phone = 1,
        SIM = 2,
        Live = 3,
        Goolgle = 4
    }

    public enum PhoneStorageEnum
    {
        Live = 1,
        Goolgle = 2
    }

    #endregion

    #region internal Class

    [Serializable]
    internal class PhoneBook
    {
        public string Name { get; set; }
        public string Number { get; set; }
        public string PhoneIndex { get; set; }
        public string SIMIndex { get; set; }
        public int RestoreIndex { get; set; }
        public override string ToString()
        {
            return Name;
        }
    }

    internal class OrderPhoneBook : IComparer<PhoneBook>
    {
        public int Compare(PhoneBook x, PhoneBook y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }

    internal class OrderReportSMS : IComparer<StatusSMSReport>
    {
        public int Compare(StatusSMSReport x, StatusSMSReport y)
        {
            string xvalue = "000000000000";
            string yvalue = "000000000000";
            if (x.DateTimeReceiver.HasValue)
            {
                xvalue = x.DateTimeReceiver.Value.Ticks.ToString().PadLeft(12, '0');
            }
            if (y.DateTimeReceiver.HasValue)
            {
                yvalue = y.DateTimeReceiver.Value.Ticks.ToString().PadLeft(12, '0');
            }
            if (x.DateTimeSend.HasValue)
            {
                xvalue = x.DateTimeSend.Value.Ticks.ToString().PadLeft(12, '0');
            }
            if (y.DateTimeSend.HasValue)
            {
                yvalue = y.DateTimeSend.Value.Ticks.ToString().PadLeft(12, '0');
            }
            return xvalue.CompareTo(yvalue);
        }
    }

    internal class OrderReportSMSDesc : IComparer<StatusSMSReport>
    {
        public int Compare(StatusSMSReport x, StatusSMSReport y)
        {
            string xvalue = "000000000000";
            string yvalue = "000000000000";
            if (x.DateTimeReceiver.HasValue)
            {
                xvalue = x.DateTimeReceiver.Value.Ticks.ToString().PadLeft(12, '0');
            }
            if (y.DateTimeReceiver.HasValue)
            {
                yvalue = y.DateTimeReceiver.Value.Ticks.ToString().PadLeft(12, '0');
            }
            if (x.DateTimeSend.HasValue)
            {
                xvalue = x.DateTimeSend.Value.Ticks.ToString().PadLeft(12, '0');
            }
            if (y.DateTimeSend.HasValue)
            {
                yvalue = y.DateTimeSend.Value.Ticks.ToString().PadLeft(12, '0');
            }
            return yvalue.CompareTo(xvalue);
        }
    }

    internal class OrderSMS : IComparer<SMSStorage>
    {
        public int Compare(SMSStorage x, SMSStorage y)
        {
            string xvalue = "";
            string yvalue = "";
            if (x.DateTime.HasValue)
            {
                xvalue = x.DateTime.Value.ToString("yyyy/MM/dd HH:mm:ss");
            }
            if (y.DateTime.HasValue)
            {
                yvalue = y.DateTime.Value.ToString("yyyy/MM/dd HH:mm:ss");
            }
            return xvalue.CompareTo(yvalue);
        }
    }

    internal class OrderSMSDesc : IComparer<SMSStorage>
    {
        public int Compare(SMSStorage x, SMSStorage y)
        {
            string xvalue = "";
            string yvalue = "";
            if (x.DateTime.HasValue)
            {
                xvalue = x.DateTime.Value.ToString("yyyy/MM/dd HH:mm:ss");
            }
            if (y.DateTime.HasValue)
            {
                yvalue = y.DateTime.Value.ToString("yyyy/MM/dd HH:mm:ss");
            }
            return yvalue.CompareTo(xvalue);
        }
    }

    internal class OrderLiveGooglePhoneBook : IComparer<LiveGooglePhoneBook>
    {
        public int Compare(LiveGooglePhoneBook x, LiveGooglePhoneBook y)
        {
            return x.OriginalName.CompareTo(y.OriginalName);
        }
    }

    [Serializable]
    internal class LiveGooglePhoneBook
    {
        public bool IsSync { get; set; }
        public string OriginalID { get; set; }
        public string OriginalName { get; set; }
        public string OriginalNumber { get; set; }
        public string OriginalNumberType { get; set; }
        public BookSyncEnum OriginalFrom { get; set; }
        public string Name { get; set; }
        public string Number { get; set; }
        public string PhoneIndex { get; set; }
        public string SIMIndex { get; set; }
    }

    [Serializable]
    internal class DefaultModem
    {
        public DefaultModem()
        {
            PortName = "";
            BaudRate = 115200;
            DataBits = 8;
            StopBits = StopBits.One;
            Handshake = Handshake.RequestToSend;
            ReadTimeout = Properties.Settings.Default.DefaultReadTimeout;
            WriteTimeout = Properties.Settings.Default.DefaultWriteTimeout;
            OpenTimeOut = Properties.Settings.Default.DefaultOpenTimeOut;
            IsTested = false;
            PortTested = "";
            Serial = "";
        }
        public string Serial { get; set; }
        public string PortName { get; set; }
        public int BaudRate { get; set; }
        public int DataBits { get; set; }
        public StopBits StopBits { get; set; }
        public Handshake Handshake { get; set; }
        public int ReadTimeout { get; set; }
        public int WriteTimeout { get; set; }
        public int OpenTimeOut { get; set; }
        public bool IsTested { get; set; }
        public string PortTested { get; set; }
    }

    [Serializable]
    internal class DefaultSeetings
    {
        public DefaultSeetings()
        {
            AutoDetect = true;
            OpenTimeOut = 8000;
            WriteTimeOut = 5000;
            ReadTimeOut = 5000;
            PoollingGoogle = 3600;
            PoollingLive = 3600;
            PoollingModem = 5;
            PoollingSMS = 300;
            PageItemsPhonebook = 15;
            PageItemsSync = 15;
            BatteryLevel = 0;
            CharSetSMS = "GSM";
            SMSReadDelete = "SM";
            SMSWriteSend = "SM";
            SMSReceiver = "SM";
            CharSetPhonebook = "GSM";
            CallCodeOper = "0XX";
            DateFormat = "MM/DD/YYYY";
            DelayCmd = 70;
            StdLenPhone = 8;
            StdLenDDD = 2;
            PhoneMDDD = "";
            PhoneM3Number = "";
            PhoneM3Name = "";
            PhoneM2Number = "";
            PhoneM2Name = "";
            PhoneM1Number = "";
            PhoneM1Name = "";
            LiveUser = "";
            LiveSaveUser = true;
            LiveSavePwd = false;
            LivePwd = "";
            GoogleUser = "";
            GoogleSaveUser = true;
            GoogleSavePwd = false;
            GooglePwd = "";
        }
        public string LiveUser { get; set; }
        public bool LiveSaveUser { get; set; }
        public bool LiveSavePwd { get; set; }
        public string LivePwd { get; set; }
        public string GoogleUser { get; set; }
        public bool GoogleSaveUser { get; set; }
        public bool GoogleSavePwd { get; set; }
        public string GooglePwd { get; set; }
        public string PhoneMDDD { get; set; }
        public string PhoneM3Number { get; set; }
        public string PhoneM3Name { get; set; }
        public string PhoneM2Number { get; set; }
        public string PhoneM2Name { get; set; }
        public string PhoneM1Number { get; set; }
        public string PhoneM1Name { get; set; }
        public bool AutoDetect { get; set; }
        public int OpenTimeOut { get; set; }
        public int WriteTimeOut { get; set; }
        public int ReadTimeOut { get; set; }
        public int PoollingGoogle { get; set; }
        public int PoollingLive { get; set; }
        public int PoollingModem { get; set; }
        public int PoollingSMS { get; set; }
        public int PageItemsPhonebook { get; set; }
        public int PageItemsSync { get; set; }
        public int BatteryLevel { get; set; }
        public string CharSetSMS { get; set; }
        public string SMSReadDelete { get; set; }
        public string SMSWriteSend { get; set; }
        public string SMSReceiver { get; set; }
        public string CharSetPhonebook { get; set; }
        public string CallCodeOper { get; set; }
        public string DateFormat { get; set; }
        public int DelayCmd { get; set; }
        public int StdLenPhone { get; set; }
        public int StdLenDDD { get; set; }
    }

    #endregion

    public class SharedLib
    {


        public static MDIPhoneManager MainForm = null;

        #region Internal Static var

        internal static CultureInfo CultureUI = null;
        internal static bool PhoneManagerStartup = false;
        internal static RangerValue PhoneBookSIMRanger = new RangerValue();
        internal static RangerValue PhoneBookMEMRanger = new RangerValue();
        internal static List<PhoneBook> PhonesBook = new List<PhoneBook>();
        internal static bool PhoneBookReadSIMOK = false;
        internal static bool PhoneBookReadMEMOK = false;
        internal static int PhoneBookSIMNameMaxLength = 0;
        internal static int PhoneBookSIMNumberMaxLength = 0;
        internal static int PhoneBookMEMNameMaxLength = 0;
        internal static int PhoneBookMEMNumberMaxLength = 0;
        internal static string NameIncomingCall = "";
        internal static int BatteryMinLevel = 0;
        internal static string NumberIncomingCall = "";
        internal static bool IsWaitIncomingCall = false;
        internal static NoCallEventEnum IsNoCallDetected = NoCallEventEnum.NoAnswer;

        internal static string ReloadWithLanguage = "";
        internal static int PollingCountModem = 0;
        internal static int PollingCountLive = 0;
        internal static int PollingCountGoogle = 0;
        internal static int PollingCountSMS = 0;
        internal static int ShowOldQtdMsg = -1;
        internal static int ShowOldQtdRep = 0;
        internal static int ShowoldNewSync = 0;
        internal static int ShowAtuNewSync = 0;
        internal static int CountOffLine = 0;
        
        internal static DefaultModem ModemConfig = new DefaultModem();

        internal static ModemGSM.Modem ModemGSM = null;
        internal static Boolean IsConfigedSMS = false;
        internal static Boolean ReadInfoLive = false;
        internal static Boolean ReadInfoGoogle = false;
        internal static Boolean ReadInfoSMS = false;
        internal static Boolean ReadInfoModem = false;
        internal static Boolean ShowPhoneBook = false;
        internal static Boolean ShowPhoneSync = false;
        internal static Boolean RunningWaitProcessThread = false;
        internal static Boolean FirstRun = false;
        internal static Boolean SaveReport = false;
        internal static Boolean ChangeDefaultSet = false;

        internal static Rijndael RijndaelAlg = Rijndael.Create();

        internal static List<LiveGooglePhoneBook> LiveContacts = new List<LiveGooglePhoneBook>();
        internal static LiveOperatingEnvironment LiveOpeEnv = null;
        internal static bool LiveIsLogin = false;
        internal static string LiveUser = "";
        internal static string LivePwd = "";

        internal static List<LiveGooglePhoneBook> GoogleContacts = new List<LiveGooglePhoneBook>();
        internal static ContactsService Googleservice = null;
        internal static bool GoogleIsLogin = false;
        internal static string GoogleUser = "";
        internal static string GooglePwd = "";

        internal static int QtdNewSMSMessage = 0;
        internal static int QtdNewSMSReport = 0;

        #endregion

        #region Assembly Attribute Accessors

        internal static string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        internal static string AssemblyVersion
        {
            get
            {
                Version ver = Assembly.GetExecutingAssembly().GetName().Version;
                return ver.Major.ToString() + "." + ver.Minor.ToString() + "." + ver.Revision.ToString();
            }
        }

        internal static string AssemblyDescription
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyDescriptionAttribute)attributes[0]).Description;
            }
        }

        internal static string AssemblyProduct
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyProductAttribute)attributes[0]).Product;
            }
        }

        internal static string AssemblyCopyright
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            }
        }

        internal static string AssemblyCompany
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCompanyAttribute)attributes[0]).Company;
            }
        }
        #endregion

        #region ControlThread

        private static int _HasWaitProcessThread = 0;

        internal static void StartWaitProcessThread()
        {
            _HasWaitProcessThread++;
            RunningWaitProcessThread = true;
            if (!SharedLib.MainForm.InvokeRequired)
            {
                SharedLib.MainForm.Cursor = Cursors.WaitCursor;
            }
            if (SharedLib.MainForm.AsyncStatusModem != null)
            {
                while (SharedLib.MainForm.AsyncStatusModem.IsAlive)
                {
                    if (!SharedLib.MainForm.InvokeRequired)
                    {
                        SharedLib.ShowMsgApp("Wait end process...");
                    }
                    Thread.Sleep(100);
                    Application.DoEvents();
                }
                if (!SharedLib.MainForm.InvokeRequired)
                {
                    SharedLib.MainForm.Enabled = true;
                }
            }
        }

        internal static void EndWaitProcessThread()
        {
            _HasWaitProcessThread--;
            if (_HasWaitProcessThread <= 0)
            {
                _HasWaitProcessThread = 0;
                RunningWaitProcessThread = false;
                if (!SharedLib.MainForm.InvokeRequired)
                {
                    SharedLib.MainForm.Cursor = Cursors.Default;
                }
                SharedLib.ShowMsgApp("");
            }
        }

        #endregion
 
        #region Mensages

        internal static void MsgAlert(string Msg)
        {
            System.Windows.Forms.MessageBox.Show(Msg, AssemblyProduct, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        internal static void MsgErro(string Msg)
        {
            System.Windows.Forms.MessageBox.Show(Msg, AssemblyProduct, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        internal static bool MsgQuestion(string Msg)
        {
            DialogResult result = System.Windows.Forms.MessageBox.Show(Msg, AssemblyProduct, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            return (result == DialogResult.Yes);
        }
        
        #endregion

        #region UserFiles

        internal static string CreateNameReport(string value)
        {
            return "PhoneManager.SMSReport." + value + ".dat";
        }

        internal static string CreateNameDefaultSettings(string value)
        {
            return "PhoneManager.Settings." + value + ".dat";
        }

        internal static string CreateNameBook(string value)
        {
            return "PhoneManager.Contacts." + value + ".dat";
        }

        internal static string CreateNameModemConfig(string value)
        {
            return "PhoneManager.Modem." + value + ".dat";
        }

        internal static string CreateNameRegisterPhone(string value)
        {
            return "PhoneManager.AtCommands." + value + ".dat";
        }

        internal static void SaveModemFileName(DefaultModem Modem, string Name)
        {
            using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, Modem);
            }
        }

        internal static void SaveDefaultSeetingsFileName(DefaultSeetings DefSeetings, string Name)
        {
            using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, DefSeetings);
            }
        }

        internal static void SaveReportFileName(List<StatusSMSReport> Report, string Name)
        {
            using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, Report);
            }
        }

        internal static DefaultSeetings LoadDefaultSeetingsFileName(string Name,string Serial)
        {
            DefaultSeetings ret = new DefaultSeetings();
            if (Name != "" && ExistUserFileName(Name))
            {
                using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    ret = (DefaultSeetings)formatter.Deserialize(fs);
                }
            }
            Properties.Settings.Default.DefaultAutoDetect = ret.AutoDetect;
            Properties.Settings.Default.DefaultBatteryMinLevel = ret.BatteryLevel;
            Properties.Settings.Default.DefaultBookItemsOfPage = ret.PageItemsPhonebook;
            Properties.Settings.Default.DefaultCharSet = ret.CharSetPhonebook;
            Properties.Settings.Default.DefaultCodeOper = ret.CallCodeOper;
            Properties.Settings.Default.DefaultDateFmt = ret.DateFormat;
            Properties.Settings.Default.DefaultDelayCommand = ret.DelayCmd;
            Properties.Settings.Default.DefaultLengthCelPhone = ret.StdLenPhone;
            Properties.Settings.Default.DefaultLengthCodeDDD = ret.StdLenDDD;
            Properties.Settings.Default.DefaultOpenTimeOut = ret.OpenTimeOut;
            Properties.Settings.Default.DefaultPollingGoogle = ret.PoollingGoogle;
            Properties.Settings.Default.DefaultPollingLive = ret.PoollingLive;
            Properties.Settings.Default.DefaultPollingModem = ret.PoollingModem;
            Properties.Settings.Default.DefaultPollingSMS = ret.PoollingSMS;
            Properties.Settings.Default.DefaultReadTimeout = ret.ReadTimeOut;
            Properties.Settings.Default.DefaultSMSCharSet = ret.CharSetSMS;
            Properties.Settings.Default.DefaultSMSReadDelete = ret.SMSReadDelete;
            Properties.Settings.Default.DefaultSMSReceiver = ret.SMSReceiver;
            Properties.Settings.Default.DefaultSMSWriteSend = ret.SMSWriteSend;
            Properties.Settings.Default.DefaultSyncItemsOfPage = ret.PageItemsSync;
            Properties.Settings.Default.DefaultWriteTimeout = ret.WriteTimeOut;
            Properties.Settings.Default.DefaultPhoneM1Name = ret.PhoneM1Name;
            Properties.Settings.Default.DefaultPhoneM1Number = ret.PhoneM1Number;
            Properties.Settings.Default.DefaultPhoneM2Name = ret.PhoneM2Name;
            Properties.Settings.Default.DefaultPhoneM2Number = ret.PhoneM2Number;
            Properties.Settings.Default.DefaultPhoneM3Name = ret.PhoneM3Name;
            Properties.Settings.Default.DefaultPhoneM3Number = ret.PhoneM3Number;
            Properties.Settings.Default.DefaultPhoneMDDD = ret.PhoneMDDD;
            Properties.Settings.Default.DefaultLiveUser = ret.LiveUser;
            Properties.Settings.Default.DefaultLivePwd = ret.LivePwd;
            Properties.Settings.Default.DefaultLiveSavePwd = ret.LiveSavePwd;
            Properties.Settings.Default.DefaultLiveSaveUser = ret.LiveSaveUser;
            Properties.Settings.Default.DefaultGoogleUser = ret.GoogleUser;
            Properties.Settings.Default.DefaultGooglePwd = ret.GooglePwd;
            Properties.Settings.Default.DefaultGoogleSavePwd = ret.GoogleSavePwd;
            Properties.Settings.Default.DefaultGoogleSaveUser = ret.GoogleSaveUser;
            Properties.Settings.Default.Save();
            if (Name != "" && !ExistUserFileName(Name))
            {
                if (SharedLib.ModemGSM.IsOpen)
                {
                    string filename = SharedLib.CreateNameDefaultSettings(SharedLib.ModemGSM.IMEI);
                    SharedLib.SaveDefaultSeetingsFileName(ret, filename);
                }
            }
            return ret;
        }

        internal static List<StatusSMSReport> ReadReportFileName(string Name)
        {
            List<StatusSMSReport> ret = new List<StatusSMSReport>();
            if (ExistUserFileName(Name))
            {
                using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    ret = (List<StatusSMSReport>)formatter.Deserialize(fs);
                }
            }
            return ret;
        }

        internal static DefaultModem ReadModemFileName(string Name)
        {
            DefaultModem ret = new DefaultModem();
            if (ExistUserFileName(Name))
            {
                using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    ret = (DefaultModem)formatter.Deserialize(fs);
                }
            }
            return ret;
        }

        internal static void SaveRegisterPhoneFileName(ModelATCommands AtCmds, string Name)
        {
            using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, AtCmds);
            }
        }

        internal static bool ExistUserFileName(string Name)
        {
            return File.Exists(Application.UserAppDataPath + "\\" + Name);
        }

        internal static ModelATCommands ReadRegisterPhoneFileName(string Name)
        {
            ModelATCommands ret = new ModelATCommands();
            if (ExistUserFileName(Name))
            {
                using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    ret = (ModelATCommands)formatter.Deserialize(fs);
                }
            }
            return ret;
        }

        internal static void SaveLiveBookFileName(PhoneStorageEnum Storage, string Name)
        {
            using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                if (Storage == PhoneStorageEnum.Live)
                {
                    formatter.Serialize(fs, SharedLib.LiveContacts);
                }
                else if (Storage == PhoneStorageEnum.Goolgle)
                {
                    formatter.Serialize(fs, SharedLib.GoogleContacts);
                }
            }
        }

        internal static void ReadPhoneBookFileName(PhoneStorageEnum Storage, string Name)
        {
            if (!ExistUserFileName(Name))
            {
                if (Storage == PhoneStorageEnum.Live)
                {
                    LiveContacts = new List<LiveGooglePhoneBook>();
                }
                else if (Storage == PhoneStorageEnum.Goolgle)
                {
                    GoogleContacts = new List<LiveGooglePhoneBook>();
                }
                return;
            }
            using (FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + Name, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                if (Storage == PhoneStorageEnum.Live)
                {
                    LiveContacts = (List<LiveGooglePhoneBook>)formatter.Deserialize(fs);
                }
                else if (Storage == PhoneStorageEnum.Goolgle)
                {
                    GoogleContacts = (List<LiveGooglePhoneBook>)formatter.Deserialize(fs);
                }
            }
        }

        #endregion

        #region FindPhonebook
        
        internal static PhoneBook FindPhoneByNumber(string Number, bool FindSIM)
        {
            PhoneBook Pb = null;
            if (Number.Trim() == "")
            {
                return Pb;
            }
            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                bool ok = false;
                if (item.Number.Trim().Length == Number.Trim().Length)
                {
                    if (item.Number.Trim() == Number.Trim())
                    {
                        ok = true;
                    }
                }
                else if (item.Number.Trim().Length > Number.Trim().Length)
                {
                    if (item.Number.Trim().Contains(Number.Trim()))
                    {
                        ok = true;
                    }
                }
                else if (item.Number.Trim().Length < Number.Trim().Length)
                {
                    if (Number.Trim().Contains(item.Number.Trim()))
                    {
                        ok = true;
                    }
                }
                if (ok)
                {
                    if (item.SIMIndex.Trim() != "" && FindSIM)
                    {
                        Pb = item;
                        break;
                    }
                    if (item.PhoneIndex.Trim() != "" && !FindSIM)
                    {
                        Pb = item;
                        break;
                    }
                }
            }
            return Pb;
        }

        internal static PhoneBook FindPhoneByName(string Name, bool FindSIM)
        {
            PhoneBook Pb = null;
            if (Name.Trim() == "")
            {
                return Pb;
            }
            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                if (item.Name.Trim().ToLower() == Name.Trim().ToLower())
                {
                    if (item.SIMIndex.Trim() != "" && FindSIM)
                    {
                        Pb = item;
                        break;
                    }
                    if (item.PhoneIndex.Trim() != "" && !FindSIM)
                    {
                        Pb = item;
                        break;
                    }
                }
            }
            return Pb;
        }

        internal static PhoneBook FindPhoneByID(string ID, bool FindSIM)
        {
            PhoneBook Pb = null;
            if (ID.Trim() == "")
            {
                return Pb;
            }
            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                if (FindSIM)
                {
                    if (item.SIMIndex.Trim() == ID)
                    {
                        Pb = item;
                        break;
                    }
                }
                else 
                {
                    if (item.PhoneIndex.Trim() == ID)
                    {
                        Pb = item;
                        break;
                    }
                }

            }
            return Pb;
        }

        internal static PhoneBook FindPhoneByRestoreID(int ID)
        {
            PhoneBook Pb = null;
            if (ID == 0)
            {
                return Pb;
            }
            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                if (item.RestoreIndex == ID )
                {
                    Pb = item;
                    break;
                }
            }
            return Pb;
        }

        internal static LiveGooglePhoneBook FindPhoneByFromLiveGoogleID(BookSyncEnum KindFrom, string TypePhone, string ID)
        {
            LiveGooglePhoneBook Pb = null;
            if (ID.Trim() == "")
            {
                return Pb;
            }
            List<LiveGooglePhoneBook> Items = null;
            if (KindFrom == BookSyncEnum.Live)
            {
                Items = LiveContacts;
            }
            else if (KindFrom == BookSyncEnum.Goolgle)
            {
                Items = GoogleContacts;
            }
            foreach (LiveGooglePhoneBook item in Items)
                {
                    if (KindFrom == BookSyncEnum.Live && item.OriginalFrom == BookSyncEnum.Live)
                    {
                        if (item.OriginalID.Trim() == ID.Trim() && item.OriginalNumberType.Trim() == TypePhone.Trim())
                        {
                            Pb = item;
                            break;
                        }
                    }
                    else if (KindFrom == BookSyncEnum.Goolgle && item.OriginalFrom == BookSyncEnum.Goolgle)
                    {
                        if (item.OriginalID.Trim() == ID.Trim() && item.OriginalNumberType.Trim() == TypePhone.Trim())
                        {
                            Pb = item;
                            break;
                        }
                    }
                }
            return Pb;
        }

        #endregion

        #region UTIL

        internal static string TranslateStatus(string Status)
        {
            ActiveStatusEnum sta = (ActiveStatusEnum)Enum.Parse(typeof(ActiveStatusEnum), Status);
            switch (sta)
            {
                case ActiveStatusEnum.Busy:
                    return ResourcesText.MsgBusy;
                case ActiveStatusEnum.NoDialtone:
                    return ResourcesText.MsgNoTone;
                case ActiveStatusEnum.NoCarrier:
                    return ResourcesText.MsgNoCarrier;
                case ActiveStatusEnum.NoAnswer:
                    return ResourcesText.MsgNoAnswer;
                case ActiveStatusEnum.Disconnected:
                    return ResourcesText.MsgDisconnected;
                case ActiveStatusEnum.Offline:
                    return ResourcesText.MsgOffline;
                case ActiveStatusEnum.Error:
                    return ResourcesText.MsgError;
                case ActiveStatusEnum.Ready:
                    return ResourcesText.MsgReady;
                case ActiveStatusEnum.Unavailable:
                    return ResourcesText.MsgUnavailable;
                case ActiveStatusEnum.unknown:
                    return ResourcesText.Msgunknown;
                case ActiveStatusEnum.Ringing:
                    return ResourcesText.MsgRinging;
                case ActiveStatusEnum.call:
                    return ResourcesText.Msgcall;
                case ActiveStatusEnum.asleep:
                    return ResourcesText.Msgasleep;
            }
            return Status;
        }

        internal static string GetValidLanguage(string lng)
        { 
            string ret = "en-US";
            if (lng.StartsWith("en"))
            {
                ret = "en-US";
            }
            if (lng == "pt-BR")
            {
                ret = "pt-BR";
            }
            if (lng.StartsWith("pt"))
            {
                ret = "pt-BR";
            }
            return ret;
        }

        internal static Image GetImageLanguage(string lng)
        {
            if (lng == "en-US")
            {
                return Properties.Resources.en_US;
            }
            if (lng.StartsWith("en"))
            {
                return Properties.Resources.en_US;
            }
            if (lng == "pt-BR")
            {
                return Properties.Resources.pt_BR;
            }
            if (lng.StartsWith("pt"))
            {
                return Properties.Resources.pt_BR;
            }
            return Properties.Resources.OnOffDisabled; 
        }

        internal static string ShowTaskWaitVisible(string Message)
        {
            string id = ShowTaskNotif(Message);
            while (Taskbar.Notifier.GetTaskbarState(id) == Taskbar.TaskbarStates.appearing)
            {
                Application.DoEvents();
            }
            return id;
        }
                
        internal static string ShowTaskNotif(string Message)
        {
            Taskbar.Notifier.NotifierMaxWidth = 180;
            Taskbar.Notifier.GradienteStartColor = Color.FromArgb(150, 206, 231);
            Taskbar.Notifier.GradienteEndColor = Color.FromArgb(255, 255, 255);
            Taskbar.Notifier.ShowGradientebackgroud = true;
            Taskbar.Notifier.TimeToHide = 700;
            Taskbar.Notifier.TimeToShow = 500;
            Taskbar.Notifier.TimeToStay = 4000;
            Taskbar.Notifier.Title = SharedLib.AssemblyTitle;
            return Taskbar.Notifier.Show(Message);
        }


        internal static void ModemReOpen()
        {
            SharedLib.ModemGSM.ReOpen();
            if (SharedLib.ModemGSM.Online)
            {
                string filename = SharedLib.CreateNameRegisterPhone(Properties.Settings.Default.LastSerial);
                if (SharedLib.ExistUserFileName(filename))
                {
                    SharedLib.ModemGSM.SetValidsAtCommand(SharedLib.ReadRegisterPhoneFileName(filename));
                }
                filename = SharedLib.CreateNameDefaultSettings(Properties.Settings.Default.LastSerial);
                DefaultSeetings defset = SharedLib.LoadDefaultSeetingsFileName(filename, Properties.Settings.Default.LastSerial);
                SharedLib.SaveDefaultSeetingsFileName(defset, filename);

                
                filename = SharedLib.CreateNameReport(Properties.Settings.Default.LastSerial);
                SharedLib.ModemGSM.SMSClearStatusReport();
                if (SharedLib.ModemGSM.ModelATCommands.SMSSendMessageCMD)
                {
                    SharedLib.ModemGSM.SMSAddRangeStatusReport(SharedLib.ReadReportFileName(filename).ToArray());
                }
                SharedLib.SaveReportFileName(SharedLib.ModemGSM.SMSStatusReport, filename);
            }
        }

        internal static void SaveSettings()
        {
            Properties.Settings.Default.Save();
            if (SharedLib.ModemGSM.IsOpen)
            {
                string filename = SharedLib.CreateNameDefaultSettings(SharedLib.ModemGSM.IMEI);
                DefaultSeetings defset = new DefaultSeetings();
                defset.AutoDetect = Properties.Settings.Default.DefaultAutoDetect;
                defset.OpenTimeOut = Properties.Settings.Default.DefaultOpenTimeOut;
                defset.WriteTimeOut = Properties.Settings.Default.DefaultWriteTimeout;
                defset.ReadTimeOut = Properties.Settings.Default.DefaultReadTimeout;
                defset.PoollingGoogle = Properties.Settings.Default.DefaultPollingGoogle;
                defset.PoollingLive = Properties.Settings.Default.DefaultPollingLive;
                defset.PoollingModem = Properties.Settings.Default.DefaultPollingModem;
                defset.PoollingSMS = Properties.Settings.Default.DefaultPollingSMS;
                defset.PageItemsPhonebook = Properties.Settings.Default.DefaultBookItemsOfPage;
                defset.PageItemsSync = Properties.Settings.Default.DefaultSyncItemsOfPage;
                defset.BatteryLevel = Properties.Settings.Default.DefaultBatteryMinLevel;
                defset.CharSetSMS = Properties.Settings.Default.DefaultSMSCharSet;
                defset.SMSReadDelete = Properties.Settings.Default.DefaultSMSReadDelete;
                defset.SMSWriteSend = Properties.Settings.Default.DefaultSMSWriteSend;
                defset.SMSReceiver = Properties.Settings.Default.DefaultSMSReceiver;
                defset.CharSetPhonebook = Properties.Settings.Default.DefaultCharSet;
                defset.CallCodeOper = Properties.Settings.Default.DefaultCodeOper;
                defset.DateFormat = Properties.Settings.Default.DefaultDateFmt;
                defset.DelayCmd = Properties.Settings.Default.DefaultDelayCommand;
                defset.StdLenPhone = Properties.Settings.Default.DefaultLengthCelPhone;
                defset.StdLenDDD = Properties.Settings.Default.DefaultLengthCodeDDD;
                defset.PhoneMDDD = Properties.Settings.Default.DefaultPhoneMDDD;
                defset.PhoneM3Number = Properties.Settings.Default.DefaultPhoneM3Number;
                defset.PhoneM3Name = Properties.Settings.Default.DefaultPhoneM3Name;
                defset.PhoneM2Number = Properties.Settings.Default.DefaultPhoneM2Number;
                defset.PhoneM2Name = Properties.Settings.Default.DefaultPhoneM2Name;
                defset.PhoneM1Number = Properties.Settings.Default.DefaultPhoneM1Number;
                defset.PhoneM1Name = Properties.Settings.Default.DefaultPhoneM1Name;
                defset.LiveUser = Properties.Settings.Default.DefaultLiveUser;
                defset.LiveSaveUser = Properties.Settings.Default.DefaultLiveSaveUser;
                defset.LiveSavePwd = Properties.Settings.Default.DefaultLiveSavePwd;
                defset.LivePwd = Properties.Settings.Default.DefaultLivePwd;
                defset.GoogleUser = Properties.Settings.Default.DefaultGoogleUser;
                defset.GoogleSaveUser = Properties.Settings.Default.DefaultGoogleSaveUser;
                defset.GoogleSavePwd = Properties.Settings.Default.DefaultGoogleSavePwd;
                defset.GooglePwd = Properties.Settings.Default.DefaultGooglePwd;
                SharedLib.SaveDefaultSeetingsFileName(defset, filename);
            }
        }

        internal static void ReadPhoneBook()
        {
            if (ModemGSM.IsOpen && ModemGSM.KeepAlive())
            {
                SharedLib.PhonesBook.Clear();

                List<PhoneStorage> SIMPB = new List<PhoneStorage>();
                SharedLib.PhoneBookSIMRanger = SharedLib.ModemGSM.ReadPBookRangeSim();
                PhoneBookMaxLength ml = SharedLib.ModemGSM.ReadPBookMaxLengthSim();
                if (ml != null)
                {
                    SharedLib.PhoneBookSIMNameMaxLength = ml.Name;
                    SharedLib.PhoneBookSIMNumberMaxLength = ml.Number;
                }
                else
                {
                    SharedLib.PhoneBookSIMNameMaxLength = 14;
                    SharedLib.PhoneBookSIMNumberMaxLength = 40;
                }
                if (SharedLib.ModemGSM.Error == "")
                {
                    SharedLib.PhoneBookMEMNameMaxLength = ml.Name;
                    SharedLib.PhoneBookMEMNumberMaxLength = ml.Number;
                    SIMPB = SharedLib.ModemGSM.ReadPBookDataFrom(StorageReadEnum.SIM, SharedLib.PhoneBookSIMRanger.Min, SharedLib.PhoneBookSIMRanger.Max, Properties.Settings.Default.DefaultCharSet);
                    if (SharedLib.ModemGSM.Error == "")
                    {
                        foreach (PhoneStorage item in SIMPB)
                        {
                            PhoneBook Pbs = new PhoneBook();
                            Pbs.Name = item.Name; ;
                            Pbs.Number = item.Number;
                            Pbs.SIMIndex = item.Index.ToString();
                            Pbs.PhoneIndex = "";
                            SharedLib.PhonesBook.Add(Pbs);
                        }
                        SharedLib.PhoneBookReadSIMOK = true;
                    }
                    else
                    {
                        SharedLib.PhoneBookReadSIMOK = false;
                    }
                }
                List<PhoneStorage> SIMME = new List<PhoneStorage>();
                SharedLib.PhoneBookMEMRanger = SharedLib.ModemGSM.ReadPBookRangePhone();
                ml = SharedLib.ModemGSM.ReadPBookMaxLengthPhone();
                if (ml != null)
                {
                    SharedLib.PhoneBookMEMNameMaxLength = ml.Name;
                    SharedLib.PhoneBookMEMNumberMaxLength = ml.Number;
                }
                else
                {
                    SharedLib.PhoneBookMEMNameMaxLength = 14;
                    SharedLib.PhoneBookMEMNumberMaxLength = 40;
                }
                if (SharedLib.ModemGSM.Error == "")
                {
                    SIMME = SharedLib.ModemGSM.ReadPBookDataFrom(StorageReadEnum.Phone, SharedLib.PhoneBookMEMRanger.Min, SharedLib.PhoneBookMEMRanger.Max, Properties.Settings.Default.DefaultCharSet);
                    if (SharedLib.ModemGSM.Error == "")
                    {
                        foreach (PhoneStorage item in SIMME)
                        {
                            PhoneBook Pbs = new PhoneBook();
                            Pbs.Name = item.Name; ;
                            Pbs.Number = item.Number;
                            Pbs.PhoneIndex = item.Index.ToString();
                            Pbs.SIMIndex = "";
                            PhoneBook pb = SharedLib.FindPhoneByNumber(item.Number.ToString(), true);
                            if (pb != null)
                            {
                                Pbs.SIMIndex = pb.SIMIndex;
                                SharedLib.PhonesBook.Remove(pb);
                            }
                            SharedLib.PhonesBook.Add(Pbs);
                        }
                        SharedLib.PhoneBookReadMEMOK = true;
                    }
                    else
                    {
                        SharedLib.PhoneBookReadMEMOK = false;
                    }
                }
                SharedLib.PhonesBook.Sort(new OrderPhoneBook());
            }
        }

        internal static int GetQtdNotSyncContacts()
        {
            int qtd = 0;
            foreach (LiveGooglePhoneBook item in SharedLib.LiveContacts)
            {
                if (!item.IsSync)
                {
                    qtd++;
                }
            }
            foreach (LiveGooglePhoneBook item in SharedLib.GoogleContacts)
            {
                if (!item.IsSync)
                {
                    qtd++;
                }
            }
            return qtd;
        }

        internal static PortFound[] ModemAutoDetect()
        {
            SharedLib.ModemConfig = new DefaultModem();
            SharedLib.ShowMsgApp("");
            SharedLib.ModemConfig.PortTested = "";
            SharedLib.ModemConfig.IsTested = false;
            SharedLib.ModemGSM.ChangePortAutoDetect += new Modem.ChangePortAutoDetectEventHandler(SharedLib.ModemGSM_ChangePortAutoDetect);

            PortFound[] ports = SharedLib.ModemGSM.AutoDetect();
            if (ports.Length != 0)
            {
                SharedLib.ShowMsgApp("");
            }
            else
            {
                SharedLib.ShowMsgApp("Not found any ports to connect.");
            }
            SharedLib.ModemGSM.ChangePortAutoDetect -= SharedLib.ModemGSM_ChangePortAutoDetect;
            return ports;
        }

        internal static void ModemGSM_ChangePortAutoDetect(object sender, AutoDetectEventArgs e)
        {
            SharedLib.ShowMsgApp(e.PortName + " checking...");
        }

        internal static System.Collections.Specialized.StringCollection GetGSMProviders()
        {
            return Properties.Settings.Default.OperatorProviders;
        }

        internal static void ShowMsgApp(string msg)
        {
            SharedLib.MainForm.StatusBarMsg.Text = msg;
            Application.DoEvents();
        }

        #endregion

        #region Encrypt/Decrypt

        private static readonly byte[] key = {145,12,32,245,98,132,98,214,6,77,131,44,221,3,9,50};

        private static readonly byte[] iv  = {15,122,132,5,93,198,44,31,9,39,241,49,250,188,80,7};

        internal static string Encrypt(string value)
        {
            string ret = "";
            if (value == "")
            {
                return ret;
            }
            using (TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider())
            {
                byte[] buffer = null;
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tripleDESCryptoServiceProvider.CreateEncryptor(key,iv), CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                        {
                            streamWriter.WriteLine(value);
                        }
                    }
                    buffer = memoryStream.ToArray();
                    ret = Encoding.Default.GetString(buffer);
                }
            }
            return ret; 
        }

        internal static string Decrypt(string value)
        {
            string ret = "";
            if (value == "")
            {
                return ret;
            }
            using (TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider())
            {
                byte[] buffer = Encoding.Default.GetBytes(value);
                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tripleDESCryptoServiceProvider.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                    {
                        using (StreamReader streamReader = new StreamReader(cryptoStream))
                        {
                            ret = streamReader.ReadLine();
                        }
                    }

                }

            }
            return ret;
        }

        #endregion

    }


}
